﻿@model Dqaqs.Data.DataSource

@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Edit</h2>

<script src="@Url.Content("~/Scripts/jsrender.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.forms.js")" type="text/javascript"></script>

@using (Html.BeginForm("Edit", "DataSource", FormMethod.Post, new { id = "mainForm" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>DataSource</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title)
        </div>

            @Html.HiddenFor(model => model.Id, new { id = "dsId" })
            @Html.HiddenFor(model => model.ProjectId, new { id = "projectId" })
            @Html.HiddenFor(model => model.Schema, new { id = "schema" })
        <div class="editor-label">
            @Html.LabelFor(model => model.Schema)
        </div>
        <div class="editor-field" id="schemaDiv">
        </div>

        <p>
            <input type="submit" value="Submit" />
        </p>
    </fieldset>
}
<script id="simpleT" type="text/x-jsrender">
<div id="schema-stuff">
       <div class="new-table"><input type="checkbox" data-type="table" data-id="{{:Name}}" onclick="tableSelected(this)"/>{{:Name}}</div>
       <div class="editor-field"> 
        {{for Columns}}
        <div class="indent"> &nbsp;</div>
        <div class="new-column" data-id="div-{{:#parent.parent.data.Name}}" >
            <input type="checkbox" data-type="column" data-table="{{:#parent.parent.data.Name}}" data-id="{{:Name}}" 
                data-iskey="{{:IsKey}}" data-datatype="{{:Type}}"
                onclick="columnSelected(this)"/> {{if IsKey==true}}*{{/if}}{{:Name}} ( {{:Type}} )
        </div>
        {{/for}}
       <div style="clear:left"></div>
</div>
</script>
<div id="submit-confirmation" style="visibility:hidden">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Changing schema on a table wil cause all uploaded data to be droped.</p>
<p>You need to upload all you data again. Are you sure you want to continue?</p>
</div>

<script language="javascript" type="text/javascript">
    function confirmSubmission() {
        $("#submit-confirmation").css("visibility", "visible");
        $("#submit-confirmation").dialog(
        {
            width: 400,
            height: 250,
            modal: true,
            title: "Warning",
            resizable: false,
            buttons: {
                "Submit": function () { $("#schema").attr("data-isdirty", false); $(this).dialog("close"); $(":submit").click(); },
                "Cancel": function () { $(this).dialog("close"); }
            }
        }
        );
    }
</script>
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

<script>

    $(function () {
        var dsId = $("#projectId").val();
        var targetId = "schemaDiv";
        $("#mainForm").submit(function () {
            if ($("#schema").attr("data-isdirty") == "true") {
                confirmSubmission();
                return false;
            }
            return true;
        });
        loadSchema(dsId, targetId);
    });

    function loadSchema(dsId, targetId) {
        $.getJSON("/Project/Schema?id=" + dsId + "&json=true", function (data) {
            $("#" + targetId).html(
                $("#simpleT").render(data.Tables)
            );
            applySchema($.parseJSON($("#schema").val()));
        });
    }

    function applySchema(sch) {
        $.each(sch.Tables, function (i, tbl) {
            $("#schema-stuff input[data-id='" + tbl.Name + "']").attr("checked", true);
            $.each(tbl.Columns, function (i, col) {
                $("#schema-stuff div[data-id='div-" + tbl.Name + "'] input[data-id='" + col.Name + "']").attr("checked", true);
            });
        });
    }

    function tableSelected(tbl) {
        //if unselected, unselect all columns
        var tblName = $(tbl).attr("data-id");
        if (!$(tbl).is(":checked")) {
            $("#schema-stuff input[data-table='" + tblName + "']").attr("checked", false);
        }
        updateSchema();
    }

    function columnSelected(col) {
        var tblName = $(col).attr("data-table");
        if ($(col).is(":checked")) {
            $("#schema-stuff input[data-id='" + tblName + "']").attr("checked", true);
        }
        updateSchema();
    }

    function updateSchema() {
        var tables = $("#schema-stuff input[data-type=table]");
        var rv = [];
        $.each(tables, function (i, tbl) {
            var item = {};
            var tableName = $(tbl).attr("data-id");
            if (!$(tbl).is(":checked")) { return; }
            item.Name = tableName;
            item.Columns = [];
            var columns = $("#schema-stuff div[data-id='div-" + tableName + "'] input[data-type='column']")
            $.each(columns, function (i, col) {
                if (!$(col).is(":checked")) { return; }
                var column = {};
                column.Name = $(col).attr("data-id");
                column.IsKey = $(col).attr("data-iskey");
                column.Type = $(col).attr("data-datatype");
                item.Columns.push(column);
            });
            rv.push(item);
        });
        rv = { Tables: rv };
        $("#schema").val(JSON.stringify(rv));
        $("#schema").attr("data-isdirty", true);
    }
</script>